package top.lanscarlos.ashcraft.repository;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import top.lanscarlos.ashcraft.pojo.LogInfo;
import top.lanscarlos.ashcraft.pojo.Seller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.repository
 *
 * @author Lanscarlos
 * @since 2022-05-26 17:45
 */
@Repository
public class SellerRepository {
    @Autowired
    private SessionFactory sessionFactory;

    public List<Seller> query() {
        return query(null);
    }

    public List<Seller> query(@Nullable String name) {
        List<Seller> sellers = new ArrayList<>();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Seller> criteria = builder.createQuery(Seller.class);
            Root<Seller> root = criteria.from(Seller.class);

            criteria.select(root);
            if (name != null) {
                criteria.where(builder.like(root.get("name"), name + "%"));
            }

            // 获取单个结果
            sellers = session.createQuery(criteria).getResultList();
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return sellers;
    }

    public boolean insert(Seller seller) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            session.save(seller);
            LogInfo info = new LogInfo(seller);
            session.save(info);
            transaction.commit();
            return true;
        } catch (Exception e) {
            if (transaction != null) transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return false;
    }
}
